<template>
  <div class="reservation-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>预订管理</span>
          <el-button type="primary" @click="handleAdd">新增预订</el-button>
        </div>
      </template>
      
      <!-- 状态筛选 -->
      <el-radio-group v-model="statusFilter" @change="loadData" style="margin-bottom: 20px">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button label="PENDING">待确认</el-radio-button>
        <el-radio-button label="CONFIRMED">已确认</el-radio-button>
        <el-radio-button label="CHECKED_IN">已入住</el-radio-button>
        <el-radio-button label="CANCELLED">已取消</el-radio-button>
      </el-radio-group>
      
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="reservationNo" label="预订号" width="180" />
        <el-table-column prop="customerName" label="客户姓名" />
        <el-table-column prop="customerPhone" label="手机号" />
        <el-table-column prop="roomNumber" label="房间号" />
        <el-table-column prop="roomTypeName" label="房型" />
        <el-table-column label="入住日期">
          <template #default="{ row }">
            {{ formatDate(row.checkInDate) }}
          </template>
        </el-table-column>
        <el-table-column label="退房日期">
          <template #default="{ row }">
            {{ formatDate(row.checkOutDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="nights" label="天数" width="60" />
        <el-table-column prop="totalAmount" label="总金额" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.statusText }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button v-if="row.status === 'PENDING'" type="success" size="small" @click="handleConfirm(row)">确认</el-button>
            <el-button v-if="row.status === 'PENDING' || row.status === 'CONFIRMED'" type="danger" size="small" @click="handleCancel(row)">取消</el-button>
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadData"
        @current-change="loadData"
      />
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑预订' : '新增预订'" width="700px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="form.customerName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="customerPhone">
              <el-input v-model="form.customerPhone" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="证件类型" prop="customerIdType">
              <el-select v-model="form.customerIdType">
                <el-option label="身份证" value="ID_CARD" />
                <el-option label="护照" value="PASSPORT" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号码" prop="customerIdNumber">
              <el-input v-model="form.customerIdNumber" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房间" prop="roomId">
              <el-select v-model="form.roomId" placeholder="请选择房间" @change="handleRoomChange">
                <el-option
                  v-for="room in availableRooms"
                  :key="room.id"
                  :label="`${room.roomNumber} - ${room.typeName} (¥${room.price})`"
                  :value="room.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入住人数">
              <el-input-number v-model="form.adults" :min="1" :max="10" style="width: 100px" />
              成人
              <el-input-number v-model="form.children" :min="0" :max="10" style="width: 100px; margin-left: 10px" />
              儿童
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入住日期" prop="checkInDate">
              <el-date-picker
                v-model="form.checkInDate"
                type="date"
                placeholder="选择入住日期"
                :disabled-date="disabledCheckInDate"
                @change="calculateAmount"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退房日期" prop="checkOutDate">
              <el-date-picker
                v-model="form.checkOutDate"
                type="date"
                placeholder="选择退房日期"
                :disabled-date="disabledCheckOutDate"
                @change="calculateAmount"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总金额" prop="totalAmount">
              <el-input v-model="form.totalAmount" readonly>
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="押金" prop="deposit">
              <el-input v-model="form.deposit">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="特殊要求" prop="specialRequests">
          <el-input v-model="form.specialRequests" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { 
  getReservationList, 
  createReservation, 
  updateReservation,
  confirmReservation,
  cancelReservation
} from '@/api/reservation'
import { getRoomsByStatus } from '@/api/room'

const loading = ref(false)
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const statusFilter = ref('')
const availableRooms = ref([])
const selectedRoom = ref<any>(null)

const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

const form = reactive({
  id: null,
  customerId: null,
  customerName: '',
  customerPhone: '',
  customerIdType: 'ID_CARD',
  customerIdNumber: '',
  roomId: null,
  checkInDate: null,
  checkOutDate: null,
  adults: 1,
  children: 0,
  totalAmount: '',
  deposit: '',
  status: 'PENDING',
  specialRequests: ''
})

const rules: FormRules = {
  customerName: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  customerPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ],
  customerIdNumber: [
    { required: true, message: '请输入证件号码', trigger: 'blur' }
  ],
  roomId: [
    { required: true, message: '请选择房间', trigger: 'change' }
  ],
  checkInDate: [
    { required: true, message: '请选择入住日期', trigger: 'change' }
  ],
  checkOutDate: [
    { required: true, message: '请选择退房日期', trigger: 'change' }
  ]
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'PENDING':
      return 'warning'
    case 'CONFIRMED':
      return 'primary'
    case 'CHECKED_IN':
      return 'success'
    case 'CANCELLED':
      return 'info'
    default:
      return 'info'
  }
}

const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const disabledCheckInDate = (date: Date) => {
  return date < new Date(new Date().setHours(0, 0, 0, 0))
}

const disabledCheckOutDate = (date: Date) => {
  if (!form.checkInDate) {
    return date < new Date(new Date().setHours(0, 0, 0, 0))
  }
  return date <= form.checkInDate
}

const handleRoomChange = (roomId: number) => {
  selectedRoom.value = availableRooms.value.find(r => r.id === roomId)
  calculateAmount()
}

const calculateAmount = () => {
  if (form.checkInDate && form.checkOutDate && selectedRoom.value) {
    const nights = Math.ceil((form.checkOutDate.getTime() - form.checkInDate.getTime()) / (1000 * 60 * 60 * 24))
    const amount = nights * parseFloat(selectedRoom.value.price)
    form.totalAmount = amount.toFixed(2)
    form.deposit = (amount * 0.5).toFixed(2) // 默认押金为总金额的50%
  }
}

const loadData = async () => {
  loading.value = true
  try {
    const res = await getReservationList({
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    let list = res.data.list
    
    // 按状态筛选
    if (statusFilter.value) {
      list = list.filter((item: any) => item.status === statusFilter.value)
    }
    
    tableData.value = list
    total.value = res.data.total
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const loadAvailableRooms = async () => {
  try {
    const res = await getRoomsByStatus('AVAILABLE')
    availableRooms.value = res.data
  } catch (error) {
    console.error(error)
  }
}

const handleAdd = () => {
  isEdit.value = false
  Object.assign(form, {
    id: null,
    customerId: null,
    customerName: '',
    customerPhone: '',
    customerIdType: 'ID_CARD',
    customerIdNumber: '',
    roomId: null,
    checkInDate: null,
    checkOutDate: null,
    adults: 1,
    children: 0,
    totalAmount: '',
    deposit: '',
    status: 'PENDING',
    specialRequests: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  isEdit.value = true
  Object.assign(form, {
    id: row.id,
    customerId: row.customerId,
    customerName: row.customerName,
    customerPhone: row.customerPhone,
    roomId: row.roomId,
    checkInDate: new Date(row.checkInDate),
    checkOutDate: new Date(row.checkOutDate),
    adults: row.adults,
    children: row.children,
    totalAmount: row.totalAmount,
    deposit: row.deposit,
    specialRequests: row.specialRequests
  })
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await updateReservation(form)
          ElMessage.success('更新成功')
        } else {
          const res = await createReservation(form)
          ElMessage.success(`预订成功，预订号：${res.data}`)
        }
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error(error)
      }
    }
  })
}

const handleConfirm = async (row: any) => {
  await ElMessageBox.confirm(
    `确定要确认预订"${row.reservationNo}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  
  try {
    await confirmReservation(row.id)
    ElMessage.success('确认成功')
    loadData()
  } catch (error) {
    console.error(error)
  }
}

const handleCancel = async (row: any) => {
  await ElMessageBox.confirm(
    `确定要取消预订"${row.reservationNo}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  
  try {
    await cancelReservation(row.id)
    ElMessage.success('取消成功')
    loadData()
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  loadData()
  loadAvailableRooms()
})
</script>

<style scoped>
.reservation-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>